package com.cn.shop.service.impl;

import com.cn.shop.dao.CommonDao;
import com.cn.shop.entity.User;
import com.cn.shop.service.LoginService;
import com.cn.shop.utils.CHECKMSG;
import com.cn.shop.utils.CheckException;
import com.cn.shop.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 登陆注册服务
 *
 * @author suhao
 * @time 2017.09.18
 * @email suhao755@gmail.com
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private CommonDao loginDao;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
    private static Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);

    /*登录、注册*/
    @Override
    public int registerUser(User user) {
        String name = user.getUsername();
        int result = loginDao.queryUserNameIsExist(name);
        if (result != 0) {//用户存在做登录处理
            return login(user.getUsername(), user.getPassword());
        }
        Date date = new Date();
        user.setCreateTime(simpleDateFormat.format(date));
        user.setUpdateTime(simpleDateFormat.format(date));
        //加密密码
        user.setPassword(MD5Util.getStringMD5(user.getPassword()));
        log.info(MD5Util.getStringMD5(user.getPassword()));
        loginDao.register(user);
        return 2;
    }

    /*登陆*/
    @Override
    public int login(String username, String password) {
        int loginResult = loginDao.login(username, password);
        if (loginResult == 0) {
            throw new CheckException(CHECKMSG.WRONG_PASSWORD);
        }
        return 1;
    }

    /*忘记密码*/
    @Override
    public boolean forget(User user) {
        String username = user.getUsername();
        int result = loginDao.queryUserNameIsExist(username);
        if (result == 0) {
            throw new CheckException(CHECKMSG.USER_NOT_EXIST);
        }
        int changeTimes = loginDao.queryUserChangePsdTimes(username);
        String newPassword = MD5Util.getStringMD5(user.getPassword());
        loginDao.forget(newPassword, changeTimes + 1, username);
        return true;
    }

}
